//
//  SinaHomeCellViewModel.swift
//  MySinaWeiBoSwiftProject
//
//  Created by apple on 2016/11/16.
//  Copyright © 2016年 WangChen. All rights reserved.
//

import UIKit


class SinaHomeCellViewModel: NSObject {
    
    
    
    
    
    //头像url
    var iconUrl: URL?
    //等级对应的图片
    var rankImage: UIImage?
    //Vip图片
    var verifitedImage: UIImage?
    
    
    //图片链接数组
    var imageURLs: [SinaPictureInfoModel]?
    
    //日期
    var creatDateStr: String{
        
        let str = getFormatDateStr()
        return str
        
    }
    
    //来源
    var sourceStr: String{
        
        let str = getSourceInfo()
        return str
    }
    
    //微博内容(属性文本)
    var originAttributeString: NSMutableAttributedString?
    var retweeterAttributeString: NSMutableAttributedString?
    
    
    
    private func dealToAttributeStrWithString(str: String) -> (NSMutableAttributedString){
        
        let patton = "\\[.*?\\]"
        let regex = try! NSRegularExpression(pattern: patton, options: [])
        
        let results = regex.matches(in: str, options: [], range: NSMakeRange(0, str.characters.count))
        
        //转变为富文本
        let strM = NSMutableAttributedString(string: str)
        
        let font = UIFont.systemFont(ofSize: 18)
        let lineHeight = font.lineHeight
        
        //遍历结果集
        for result in results.reversed() {
            
            let range = result.range
            let subStr = (str as NSString).substring(with: range)
          
            
            if let em = HMEmoticonTools.sharedEmoticonTools.findEmotion(chs: subStr) {
                let image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
                
                let imageText = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit, attachmentSize: CGSize(width: lineHeight, height: lineHeight), alignTo: font, alignment: .center)
                
                strM.replaceCharacters(in: range, with: imageText)
            }
        }
        
        //添加属性
        strM.addAttributes([NSFontAttributeName : font], range: NSMakeRange(0, strM.length))
        
        setHightlightState(pattern: "@\\w+", strM: strM, color: #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1))
        setHightlightState(pattern: "#.*?#", strM: strM, color: #colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1))
        setHightlightState(pattern: "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?", strM: strM, color: #colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1))
        
        return strM
    }
    
    
    
    // MARK:
    // MARK: - 设置高亮状态
    func setHightlightState(pattern: String, strM: NSMutableAttributedString, color: UIColor) {
        
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        let str = strM.string
        
        let results = regex.matches(in: str, options: [], range: NSMakeRange(0, str.characters.count))
        
        for result in results {
            
            let range = result.rangeAt(0)
            
            strM.addAttributes([NSForegroundColorAttributeName : color], range: range)
            
            let border = YYTextBorder(fill: #colorLiteral(red: 0.9568627477, green: 0.6588235497, blue: 0.5450980663, alpha: 1), cornerRadius: 3)
            let hightLight = YYTextHighlight()
            hightLight.setColor(UIColor.blue)
            hightLight.setBackgroundBorder(border)
            
            strM.yy_setTextHighlight(hightLight, range: range)
            
        }
    }
    
    
    
    

    var statusModel: SinaStatusModel?{
        didSet{
            
            iconUrl = URL(string: statusModel?.user?.avatar_large ?? "")
            dealRankImage()
            dealVerifiedImage()
            
            getImageURLs()
            
            originAttributeString = dealToAttributeStrWithString(str: statusModel?.text ?? "")
            retweeterAttributeString = dealToAttributeStrWithString(str: statusModel?.retweeted_status?.text ?? "")
            
        }
    }
    
    
    // MARK:
    // MARK: - 得到图片数组
    private func getImageURLs(){
        
        if statusModel?.retweeted_status != nil {
            imageURLs = statusModel?.retweeted_status?.pic_urls
        }else{
            imageURLs = statusModel?.pic_urls
        }
        
    }
    
    
    
    
    
    // MARK:
    // MARK: - 处理等级对应图片
    private func dealRankImage(){
        let mbrank = statusModel?.user?.mbrank ?? 0
        if mbrank > 0 && mbrank < 7 {
            //赋值
            rankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
    }
    
    
    // MARK:
    // MARK: - 处理vip图片
    private func dealVerifiedImage(){
        //微博认证的图片
        let type = statusModel?.user?.verified_type ?? -1
        //判断type
        switch type {
        case 0:
            verifitedImage = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            verifitedImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            verifitedImage = #imageLiteral(resourceName: "avatar_grassroot")
        default:
            //没有认证
            verifitedImage = nil
        }
    }
    
    
    
    
    // MARK:
    // MARK: - 得到格式化日期输出的方法
    // Sat Nov 19 22:02:49 +0800 2016
    private func getFormatDateStr()->String{
        
        let format = DateFormatter()
        format.locale = Locale(identifier: "en")
        
        format.dateFormat = "EEE MMM dd HH:mm:SS Z yyyy"
        guard let sinaDate = format.date(from: statusModel?.created_at ?? "") else{
            return "穿越时空了"
        }
        
        //利用calendar来判断时间
        let calendar = NSCalendar.current
        let currentDate = Date()
        
        //获得日期比较结果
        let result = calendar.dateComponents([.day,.year], from: sinaDate, to: currentDate)
        
        //先比较年份
        //当年
        if result.year == 0{
            //今天
            if calendar.isDateInToday(sinaDate){
                //比较当前时间与sinaDate秒的差值
                let delta = currentDate.timeIntervalSince(sinaDate)
                //一分钟内
                if delta < 60 {
                    return "\(Int(delta))秒前"
                }else if delta < 3600 {
                    return "\(Int(delta / 60))分钟前"
                }else{
                    return "\(Int(delta / 3600))小时前"
                }
                //昨天
            }else if calendar.isDateInYesterday(sinaDate){
                format.dateFormat = "昨天 HH:mm"
                return format.string(from: sinaDate)
            }else{
                format.dateFormat = "MM-dd HH:mm"
                return format.string(from: sinaDate)
            }
        }else{
            //非当年
            format.dateFormat = "yyyy-MM-dd"
            return format.string(from: sinaDate)
        }
    }
    
    
    
    // MARK:
    // MARK: - 微博来源方法
    /*
     "<a href=\"http://app.weibo.com/t/feed/3jskmg\" rel=\"nofollow\">iPhone 6s</a>"
     */
    func getSourceInfo() -> String {
        
        let beginFlag = "\">"
        let endFlag = "</a>"
        
        let oldStr = statusModel?.source
        
        guard let startRange = oldStr?.range(of: beginFlag), let endRange = oldStr?.range(of: endFlag) else {
            return "来自火星"
        }
        
        let range = startRange.upperBound ..< endRange.lowerBound
        let newStr = oldStr!.substring(with: range)
        
        return newStr
    }
    
    
}
